package com.party.admin.biz.notify;

import com.google.common.base.Function;
import com.party.admin.web.dto.input.common.CommonQuery;
import com.party.admin.web.dto.output.notify.TemplateOutput;
import com.party.common.constant.Constant;
import com.party.common.paging.Page;
import com.party.common.utils.LangUtils;
import com.party.core.model.notify.TargetTemplate;
import com.party.core.model.notify.TargetTemplateType;
import com.party.core.model.notify.TargetTemplateWithQuery;
import com.party.core.service.crowdfund.ITargetTemplateService;
import com.party.core.service.notify.IInstanceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 短信模板业务接口
 * Created by wei.li
 *
 * @date 2017/10/13 0013
 * @time 14:17
 */

@Service
public class MessageTemplateBizService {

    @Autowired
    private ITargetTemplateService targetTemplateService;

    @Autowired
    private IInstanceService instanceService;

    /**
     * 短信模板列表
     *
     * @param targetTemplateWithQuery 查询参数
     * @param page 分页参数
     * @return 模板列表
     */
    public List<TemplateOutput> list(TargetTemplateWithQuery targetTemplateWithQuery, Page page){

        if (null != targetTemplateWithQuery.getTimeType() && !new Integer(0).equals(targetTemplateWithQuery.getTimeType())) {
            CommonQuery commonQuery = new CommonQuery();
            commonQuery.setTimeType(targetTemplateWithQuery.getTimeType());
            targetTemplateWithQuery.setCreateStart(commonQuery.getCreateStart());
            targetTemplateWithQuery.setCreateEnd(commonQuery.getCreateEnd());
        }

        List<TargetTemplate> list = targetTemplateService.listWithQueryPage(targetTemplateWithQuery, page);
        List<TemplateOutput> outputList = LangUtils.transform(list, new Function<TargetTemplate, TemplateOutput>() {
            @Override
            public TemplateOutput apply(TargetTemplate targetTemplate) {
                TargetTemplateType targetTemplateType = TargetTemplateType.get(targetTemplate.getType());
                TemplateOutput templateOutput = TemplateOutput.transform(targetTemplate);
                if (targetTemplateType.getType().equals(0)){
                    templateOutput.setModule("众筹");
                }
                else {
                    templateOutput.setModule("活动");
                }

                Integer successNum = instanceService.countByResult(Constant.IS_SUCCESS, targetTemplate.getId());
                Integer failureNum = instanceService.countByResult(Constant.IS_FAIL, targetTemplate.getId());
                templateOutput.setSuccessNum(successNum);
                templateOutput.setFailureNum(failureNum);
                return templateOutput;
            }
        });
        return outputList;
    }
}
